package com.qsl.juc.thread_pool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class FutureTaskDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {


        // state 的值 NEW=0, COMPLETING=1, NORMAL=2, EXCEPTIONAL=3, CANCELLED=4, INTERRUPTING=5, INTERRUPTED=6
        // Possible state transitions:
        //  NEW -> COMPLETING -> NORMAL
        //  NEW -> COMPLETING -> EXCEPTIONAL
        //  NEW -> CANCELLED
        //  NEW -> INTERRUPTING -> INTERRUPTED

        // Treiber栈里面存放的 WaitNode 代表了正在等待任务执行结束的线程

        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println("进入 子线程");
            System.out.println("线程是否被中断 : " + Thread.interrupted());
            TimeUnit.SECONDS.sleep(3);
            System.out.println("线程是否被中断 : " + Thread.interrupted());
            return 1024;
        });

        Thread t = new Thread(task);
        t.start();
        LockSupport.park();

        // 测试 state：INTERRUPTED 和 CANCELLED
        //TimeUnit.SECONDS.sleep(1);
        //task.cancel(true);
        //task.cancel(false);

        // 测试 task 执行完（state != NEW），其他线程再调度 task，task 不会再执行
        /*TimeUnit.SECONDS.sleep(4);
        new Thread(task).start();*/

        // 自旋等待 task 完成
        /*while(!task.isDone()) {
            System.out.println("自旋中");
        }*/


        // task.get 会阻塞当前线程，直至 task 执行完后被唤醒
        //System.out.println("主线程完成..." + task.get());
    }

}
